package com.whoisaa.wifitransfer.ui;

import android.content.IntentFilter;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.Toast;

import com.whoisaa.wifitransfer.R;
import com.whoisaa.wifitransfer.WifiReceiver;
import com.whoisaa.wifitransfer.WifiTools;
import com.whoisaa.wifitransfer.base.BaseActivity;
import com.whoisaa.wifitransfer.ui.activity.ChooseFileActivity;
import com.whoisaa.wifitransfer.ui.activity.ReceiverActivity;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {

    private WifiTools mWifiTools;
    private WifiReceiver mWifiReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mWifiTools = new WifiTools(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    //创建Wi-Fi热点
    public void openWifiAp() {
        WifiConfiguration configuration = mWifiTools.getWifiApConfig(WifiTools.WIFI_NAME, WifiTools.WIFI_PWD, WifiTools.WPA2_PSK);
        if (mWifiTools.openWifiAp(configuration)) {
            Toast.makeText(this, "创建成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "创建失败", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick(R.id.btn_main_send)
    public void sendFile() {
        pushActivity(ChooseFileActivity.class);
    }

    @OnClick(R.id.btn_main_receive)
    public void receiveFile() {
        pushActivity(ReceiverActivity.class);
    }

    //关闭Wi-Fi热点
    public void closeWifiAp() {
        WifiConfiguration configuration = mWifiTools.getWifiApConfig(WifiTools.WIFI_NAME, WifiTools.WIFI_PWD, WifiTools.WPA2_PSK);
        mWifiTools.closeWifiAp(configuration);
    }

    //连接指定Wi-Fi
    public void connectWifi() {
        registerReceiver();
        mWifiTools.connectWifi(WifiTools.WIFI_NAME, WifiTools.WIFI_PWD);
    }

    //断开指定Wi-Fi
    public void disconnectWifi() {
        mWifiTools.disconnectWifi(WifiTools.WIFI_NAME);
    }

    /**
     * 注册Wi-Fi网络状态监听器
     */
    private void registerReceiver() {
        if (mWifiReceiver == null) {
            mWifiReceiver = new WifiReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(mWifiReceiver, intentFilter);
    }

    /**
     * 反注册Wi-Fi网络状态监听器
     */
    private void unregisterReceiver() {
        unregisterReceiver(mWifiReceiver);
    }
}
